#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

// #define SERVER "192.168.43.166"
#define SERVER "127.0.0.1"
#define PORT 8080
#define BUFFER_SIZE 2048

const char *outfile = "src/config/netconf_mdfile/client_output.xml";
const char *infile = "src/config/netconf_mdfile/client_input.xml";
int main()
{
    int sock_fd;
    struct sockaddr_in server_addr;
    char buffer[BUFFER_SIZE];

    // 创建套接字
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0)
    {
        perror("Could not create socket");
        exit(1);
    }

    // 设置服务器地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(SERVER);
    server_addr.sin_port = htons(PORT);

    // 连接到服务器
    if (connect(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        perror("Connect failed");
        exit(1);
    }

    while (1)
    {
        // 读取xml文件
        char c;
        printf("请输入：");
        scanf(" %c", &c);
        // if (c == 'c')
        // {
        //     send(sock_fd, buffer, 0, 0);
        //     continue;
        // }
        FILE *file;
        ssize_t bytes_read;
        file = fopen(outfile, "rb");
        if (file == NULL)
        {
            perror("fopen");
            return -1;
        }
        memset(buffer, 0, sizeof(buffer));
        bytes_read = fread(buffer, 1, BUFFER_SIZE, file);
        if (bytes_read == -1)
        {
            perror("fread");
        }

        fclose(file);
        // return bytes_read;

        // 向服务器发送数据
        send(sock_fd, buffer, strlen(buffer), 0);
        printf("已发送, 长度是%ld\n", strlen(buffer));
        memset(buffer, 0, sizeof(buffer));
        // 接收响应
        int bytes = read(sock_fd, buffer, BUFFER_SIZE);
        // 解析xml文件
        if (bytes == 0)
        {
            return 0;
        }
        printf("已接受响应\n");
        file = fopen(infile, "w");
        if (file == NULL)
        {
            perror("无法打开hello文件");
            return 0;
        }
        bytes_read = fwrite(buffer, sizeof(char), bytes, file);
        printf("已写入文件\n");
        // sleep(3);
        fclose(file);
    }

    // 关闭套接字
    close(sock_fd);
    return 0;
}
